define([
    'Util',
    'list',
    'dialog',
    'select',
    'text!tpl/buildInstance/viewConstructInstance.tpl',
    'text!tpl/buildInstance/viewConstructInstanceTable.tpl',
    'tab',
    'cookie',
    '../common/getPath',
    'form',
    'clipboard',
    '../common/getQueryString',
    '../common/dateFormat'
], function(Util, List, Dialog, Select, viewConstruct, viewConstructTable, Tab, $cookie, AjaxPath, Form, Clipboard, getQueryString) {
    require(['style!css/style.css']);
    var $el=null,
        timerGet=null,
        _indexModule = null,
        viewConstructData=null,
        list = null,
        timer=null,
        tab = null,
        tplId = null,
        getResult=null;


    var initialize = function(indexModule, options, tabItem){
        $el = $(viewConstruct);
        _indexModule = indexModule;
        viewConstructData=options;
        // 事件--点击切换tab后事件回调
        $(tabItem).on("tabActive", function() {
            tabItem.show(true); // 刷新表单
        });
        // console.log(viewConstructData);
        tab = tabItem;
        this.content=$el;
        tplId = options.menuId;
        getConstruct();
        eventInit();
    };
    /*查看执行刷新*/
    var timerGetConstruct=function () {
        timerGet=setInterval(function () {
            getConstruct();
        },3000);
    };
    /*查看构建实例*/
    var getConstruct=function () {
        clearInterval(timerGet);
        Util.ajax.getJson(AjaxPath.cicd+"/ci/build/getBuildPipelineById/"+viewConstructData.systemId, {}, function(result, isok) {
            if(result.returnCode==="0000"){
                getResult=result.beans;
                $("#viewBuildStatusStartTime", $el).html(new Date(getResult.startTime).Format('yyyy-MM-dd hh:mm:ss'));
                $("#viewBuildStatusEndTime", $el).html(new Date(getResult.endTime).Format('yyyy-MM-dd hh:mm:ss'));
                //console.log(result);
                var getStatusType=function () {
                    getResult.startTimeDate = new Date(getResult.startTime).Format('yyyy-MM-dd hh:mm:ss');
                    getResult.endTimeDate = new Date(getResult.endTime).Format('yyyy-MM-dd hh:mm:ss');
                    //getResult.totalTimeStr = new Date(getResult.totalTime).Format('mm分ss秒');
                    $(".viewConstructTable", $el).html(Util.hdb.compile(viewConstructTable)(getResult));
                    var viewInstance="/ 查看构建实例:"+getResult.ciName+" / "+getResult.caseCode;
                    var qualityAnalysisReport='<a href="'+getResult.qualityAnalysisReportUrl+'" class="qualityBtn" style="color:#187dff; ">'+(getResult.qualityAnalysisReport ? getResult.qualityAnalysisReport : '')+'</a>';
                    var applicationName='<a href="'+getResult.applicationUrl+'" class="applicationBtn"style="color:#3476ff; ">'+(getResult.applicationName ? getResult.applicationName : '')+'</a>';
                    var mirrorPackageName='<a href="'+getResult.mirrorPackageUrl+'" class="mirrorBtn"style="color:#2e81ff; ">'+(getResult.mirrorPackageName ? getResult.mirrorPackageName : '')+'</a>';
                    $(".viewInstance",$el).html(viewInstance);
                    $(".viewCode",$el).html(getResult.caseCode +" , ");
                    var AllTime="";
                    if(getResult.totalTime<1000){
                        AllTime=getResult.totalTime+"ms";

                    }else if(getResult.totalTime>60*1000){
                        AllTime=new Date(getResult.totalTime).Format('mm分ss秒')
                    }else{
                        AllTime=parseInt(getResult.totalTime/1000)+"s";
                    }
                    $(".viewTotalTime",$el).html('耗时'+AllTime);
                    $(".totalTimeStr",$el).html(AllTime);
                    $(".qualityAnalysisReport",$el).html(qualityAnalysisReport);
                    $(".applicationName",$el).html(applicationName);
                    $(".mirrorPackageName",$el).html(mirrorPackageName);
                };
                getStatusType();
                var recordActive="";
                var intPipelinesContent = '';
                var oneBuildInstanceLogs="";
                var triLeft = '';
                var isShow = '';
                var isFailed =-1;
                var isDoing=-1;
                var starLogContent = "";
                var oneStart="";
                var oneStartI="";
                for( var k = 0; k < getResult.buildInstanceNodes.length; k++) {
                    var viewConstructFail = 0;
                    for (var i=0; i<getResult.buildInstanceLogs.length;i++) {
                        var recordContent="";
                        /*日志中状态的标志*/
                        if(getResult.buildInstanceLogs[i].isSuccess===-1 ){
                            isFailed = i;
                            recordContent+='<li style="color:red">'+getResult.buildInstanceLogs[i].logString +'</li> ';
                        }else if(getResult.buildInstanceLogs[i].isSuccess===1 ){
                            recordContent+='<li>'+getResult.buildInstanceLogs[i].logString +'</li> ';
                        }else if(getResult.buildInstanceLogs[i].isSuccess===0){
                            isDoing=i;
                            //console.log(isDoing)
                            recordContent+='<li style="color:#ffda48;">'+getResult.buildInstanceLogs[i].logString+'</li> ';
                        }
                        var activeStyle = 'background:none';
                        var useTime="";
                        if(getResult.buildInstanceLogs[i].useTime<1000){
                            useTime='耗时' + getResult.buildInstanceLogs[i].useTime+"ms";

                        }else if(getResult.buildInstanceLogs[i].useTime>60*1000){
                            useTime='耗时' + new Date(getResult.buildInstanceLogs[i].useTime).Format('mm分ss秒')
                        }else{
                            useTime='耗时' + parseInt(getResult.buildInstanceLogs[i].useTime/1000)+"s";
                        }
                /*获取流水线和日志*/
                        if( getResult.buildInstanceLogs[i].localNodeId===getResult.buildInstanceNodes[k].nodeId){
                            viewConstructFail = 1;
                            intPipelinesContent += ' <li class="fn-fl new_clearfix border_one" style="margin-left:10px;" > ' +
                                '<div class="new_li fn-fl" style="background: #eff6fc;" > ' + getResult.buildInstanceNodes[k].nodeName + '</div> ' +
                                '<i class="iconfont icon-chiping" style="float: right; margin: 18px 0 0 20px;"></i> ' +
                                '<p class="clearfix pt-5" style="padding-left: 12px;">'+useTime+ '</p>' +
                                '</li>';

                            recordActive+='<li class="selected" style="margin: 5px 0 5px 0;"> ' +
                                '<div class="t-list-title sliderMakeContainer  sliderContainer"> ' +
                                '<div class="header_start" style="float: left;">' +
                                '<h2 style="height:100%;"> ' +
                                '<i class="icon_circle icon_circle_true icon_header">√</i> ' +
                                '<em class="icon_side viewRecord">'+getResult.buildInstanceNodes[k].nodeName+'</em> '+
                                '</h2> ' +
                                '</div>'+
                                '<span class="tri tri-down '+ triLeft +'" style="margin-top:10px;"></span> ' +
                                '</div> ' +
                                '<div class="appendixContainer makeContent change_off " style="'+ isShow +'"> ' +
                                '<h3 class="viewGetTime">'+getResult.buildInstanceLogs[i].starTime+'&nbsp;'+getResult.buildInstanceNodes[k].nodeName+'</h3> ' +
                                '<ol class="viewOl"> ' +recordContent+
                                '</ol> ' +
                                '</div> ' +
                                '</li>';
                        }
                    }
                /*失败获取流水线和失败之后显示的日志*/
                    if(viewConstructFail === 0){
                        intPipelinesContent += ' <li class="fn-fl new_clearfix border_one" style="margin-left:10px;" > ' +
                            '<div class="new_li fn-fl" style="' + activeStyle + '"> ' + getResult.buildInstanceNodes[k].nodeName + '</div> ' +
                            '<i class="iconfont icon-chiping" style="float: right; margin: 18px 0 0 20px;"></i> ' +
                            '<p class="clearfix pt-5" style="padding-left: 5px;"></p>' +
                            '</li>';

                        recordActive+='<li class="selected" style="margin: 5px 0 5px 0;"> ' +
                            '<div class="t-list-title sliderMakeContainer  sliderContainer"style="background: #f2f2f2;"> ' +
                            '<div class="header_start" style="float: left;">' +
                            '<h2 style="height:100%;"> ' +
                            '<i class="icon_circle icon_circle_true icon_header" style="border-radius:50%;background:#999">'+(k+2)+'</i> ' +
                            '<em class="icon_side viewRecord">'+getResult.buildInstanceNodes[k].nodeName+'</em> '+
                            '</h2> ' +
                            '</div>'+
                            '<span class="tri tri-down " style="margin-top:10px;"></span> ' +
                            '</div> ' +
                            '</li>';

                    }

                }
                /*执行三个状态的样式1,0，-1*/
                if(getResult.buildInstanceLogs.length<0){
                    oneStart="background:#f2f2f2";
                    oneStartI="background:#999";
                }
                if(getResult.buildInstanceLogs.length > 0){
                    starLogContent = getResult.buildInstanceLogs[0].logString;
                }
                /*添加日志开始第一条*/
                oneBuildInstanceLogs='<li class="selected" style="margin: 5px 0 5px 0; "> ' +
                    '<div class="t-list-title sliderMakeContainer  sliderContainer" style="'+oneStart+'"> ' +
                    '<div class="header_start" style="float: left;">' +
                    '<h2 style="height:100%;"> ' +
                    '<i class="icon_circle icon_circle_true icon_header" style="border-radius:50%;'+oneStartI+'">√</i> ' +
                    '<em class="icon_side viewRecord">开始</em> '+
                    '</h2> ' +
                    '</div>'+
                    '<span class="tri tri-down '+ triLeft +'" style="margin-top:10px;"></span> ' +
                    '</div> ' +
                    '<div class="appendixContainer makeContent change_off " style="display: none;"> ' +
                    '<h3 class="viewGetTime">'+getResult.startTimeDate+'</h3> ' +
                    '<ol class="viewOl"> ' +starLogContent  +
                    '</ol> ' +
                    '</div> ' +
                    '</li>';
                $('#new_state_box', $el).html(intPipelinesContent);
                $('.recordActive',$el).html(oneBuildInstanceLogs+recordActive);
                //constructRecord();
                if(isFailed >=0){
                    $('.recordActive',$el).children('li').eq(isFailed).find('.sliderMakeContainer').css({
                        "background-color":"rgba(255, 238, 255, 1)",
                        "border": "1px solid rgba(195, 0, 0, 1)"
                    }).find('i').css({
                        "background":"#c30000",
                        "borderRadius":"50%"
                    }).html("X");
                    if(isFailed>0){
                        $('.recordActive',$el).children('li').eq(isFailed).find('.makeContent').css({
                            "display":"block"
                        });
                        $('.new_stateul li',$el).eq(isFailed-1).find('.new_li ').css({
                            "background-color":"rgba(255, 238, 255, 1)",
                            "border": "1px solid rgba(195, 0, 0, 1)"
                        });
                        $('.new_stateul li',$el).eq(isFailed-1).find('p').html('执行失败').css("color","#c30000");
                    }
                }
                //console.log(isDoing);
                if(isDoing>=0){
                    $('.recordActive',$el).children('li').eq(isDoing).find('.sliderMakeContainer').css({
                        "background-color":"rgba(255, 255, 153, 1)"
                    }).find('i').css({
                        "background":"#ffcc00",
                        "borderRadius":"50%"
                    }).html("...");
                    //console.log(isDoing);
                    if(isDoing>0){
                        //console.log(isDoing);
                        $('.recordActive',$el).children('li').eq(isDoing).find('.makeContent').css({
                            "display":"block"
                        });
                        $('.new_stateul li',$el).eq(isDoing-1).find('.new_li ').css({
                            "background-color":"#addef0"
                        });
                        $('.new_stateul li',$el).eq(isDoing-1).find('p').html('&nbsp;&nbsp;&nbsp;执行中').css("color","#0085D0");
                    }

                }
                /*三个判断状态*/
                if(getResult.statusType===0){
                    /*执行中*/
                    timerGetConstruct();
                    $(".constructStatus em",$el).html("执行中 , ");
                    $(".statusTypeStart",$el).html("执行中");
                }else if(getResult.statusType===-1){
                    $(".constructInstance",$el).css({
                        "backgroundColor":"rgba(255, 238, 255, 1)",
                        "border": "1px solid rgba(195, 0, 0, 1)"
                    });
                    getStatusType();
                    $(".constructStatus em",$el).html("执行失败 , ");
                    $(".statusTypeStart",$el).html("执行失败");

                }else if(getResult.statusType===1){
                    $(".constructInstance",$el).css({
                        "backgroundColor":"rgba(237, 248, 232, 1)"
                    });
                    getStatusType();
                    $(".constructStatus em",$el).html("执行成功 , ");
                    $(".statusTypeStart",$el).html("执行成功");
                }
            }else {
                config = {
                    mode: 'confirm', // 对话框模式，默认normal标准|confirm浮动层|confirm确认对话框
                    title:'提示',
                    width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                    height: 120, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                    cancelDisplay: false, //是否显示取消按钮（强制执行，可在confirm模式下生效），可选项。 默认true(显示)
                    modal:true,
                    content: '<div style="text-align:center;margin-top:50px">'+result.returnMessage+'</div>' // 对话框内容，可以是字符串、html片段、或dom对象,默认为loading状态（点组成的圈）
                };
                new Dialog(config);
            }
        });
    };
    //折叠三角
    var changeSlide = function (){
        $(this).toggleClass('tri-left');
        $(this).parent().siblings().stop().slideToggle();
        // $(this).parents('li').find('.appendixContainer').slideUp();
    };
    var changeSlideBox = function (){
        $(this).find('.tri').toggleClass('tri-left');
        $(this).siblings().stop().slideToggle();
    };
    var tabActive = function() {

    };
    //按钮事件
    var btnBack = function() {
        tab.switchTab(viewConstructData.menuId);
        tab.destroy("viewConstructInstance");
        $(".ui-popup-backdrop, .ui-popup,.ui-popup-modal,.ui-popup-show,.ui-popup-focus").remove();
    };
    var eventInit = function (){
        //页面除dialog按钮功能
        $el.on('click', '.btnBack' +
            ']66ftff6', btnBack);//返回
        //$el.on('click', '.recordActive .sliderMakeContainer ', changeSlideBox);//折叠
        $el.on('click', '.tabConstructContainer .tri', changeSlide);//折叠
        $('#tabList li.' + tplId).on('click', tabActive);
    };


    return initialize;
});